package com.jakewharton.rxbinding4.component;

import static com.jakewharton.rxbinding4.internal.Preconditions.checkMainThread;

import com.jakewharton.rxbinding4.InitialValueObservable;

import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.openharmony.MainThreadDisposable;
import ohos.agp.components.Slider;

final class SeekBarChangeEventObservable extends InitialValueObservable<SeekBarChangeEvent> {
    private final Slider view;

    SeekBarChangeEventObservable(Slider view) {
        this.view = view;
    }

    @Override
    protected void subscribeListener(Observer<? super SeekBarChangeEvent> observer) {
        if (!checkMainThread(observer)) {
            return;
        }
        Listener listener = new Listener(view, observer);
        view.setValueChangedListener(listener);
        observer.onSubscribe(listener);
    }

    @Override
    protected SeekBarChangeEvent getInitialValue() {
        return SeekBarProgressUpdateEvent.create(view, view.getProgress(), false);
    }

    static final class Listener extends MainThreadDisposable implements Slider.ValueChangedListener {
        private final Slider view;
        private final Observer<? super SeekBarChangeEvent> observer;

        Listener(Slider view, Observer<? super SeekBarChangeEvent> observer) {
            this.view = view;
            this.observer = observer;
        }

        @Override
        protected void onDispose() {
            view.setValueChangedListener(null);
        }

        @Override
        public void onProgressUpdated(Slider slider, int progress, boolean fromUser) {
            if (!isDisposed()) {
                observer.onNext(SeekBarProgressUpdateEvent.create(slider, progress, fromUser));
            }
        }

        @Override
        public void onTouchStart(Slider slider) {
            if (!isDisposed()) {
                observer.onNext(SeekBarStartChangeEvent.create(slider));
            }
        }

        @Override
        public void onTouchEnd(Slider slider) {
            if (!isDisposed()) {
                observer.onNext(SeekBarStopChangeEvent.create(slider));
            }
        }
    }
}
